//
//  OauthViewController.swift
//  weibo1990
//
//  Created by 曹晓龙 on 15/10/19.
//  Copyright © 2015年 曹晓龙. All rights reserved.
//

import UIKit
import SVProgressHUD

/// Oauth 授权界面
class OauthViewController: UIViewController {

    private var webView:UIWebView?
    
    override func loadView() {
        
        webView = UIWebView()
        
        webView?.delegate = self
        
        view = webView
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        view.backgroundColor = UIColor.lightGrayColor()
        
        setupUI()
        
        loadData()

    }

    ///  推出授权页面
    @objc private func close(){
        
        SVProgressHUD.dismiss()
        
        dismissViewControllerAnimated(true, completion: nil)
        
    }
    
    ///  自动填充账号密码
    @objc private func fillPassWord(){
        
        let js = "document.getElementById('userId').value = '18737124971';"+"document.getElementById('passwd').value = 'cxl18737124971';"
        
        webView?.stringByEvaluatingJavaScriptFromString(js)
    }
    
    ///  设置UI界面
    private func setupUI() {
        
        navigationItem.title = "登录界面"
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: UIBarButtonItemStyle.Plain, target: self, action: "fillPassWord")
        
    }
    
    func loadData(){
        webView?.loadRequest(NSURLRequest(URL: CXLAFNMangerTool.sharedAFNMangerTool.oauthUrl))
    }

}


// MARK: - webView的代理方法
extension OauthViewController:UIWebViewDelegate {
 
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        guard let url = request.URL where url.host == "www.baidu.com" else{
            return true
        }
        
        guard let query = url.query where query.hasPrefix("code=") else {
            
            
            SVProgressHUD.showErrorWithStatus("未获得权限,请新登录")
            
            dispatch(1.0){ self.close() }
            
            return false
        }
        
        let code = query.substringFromIndex("code=".endIndex)

        // 获取令牌
        
        OauthViewModel.sharedOauthViewModel.getToken2LoadUserInfo(code) { (isSuccessed) -> () in
            
            if !isSuccessed {
                
                print("加载出错")
                
                SVProgressHUD.showErrorWithStatus("你的网络不给力.请重试")
                
                dispatch(1.0){ self.close() }
                
                return
            }
            
            // 保存当前版本号
            
            let currentVersion = Double(NSBundle.mainBundle().infoDictionary!["CFBundleShortVersionString"] as! String) ?? 0.0
            
            let preVersionKey = "preVersionKey"
            
            NSUserDefaults.standardUserDefaults().setDouble(currentVersion, forKey: preVersionKey)
            NSUserDefaults.standardUserDefaults().synchronize()
            
            self.dismissViewControllerAnimated(false, completion: { () -> Void in
                
                SVProgressHUD.dismiss()
                
                NSNotificationCenter.defaultCenter().postNotificationName(WBSwiftNotificationKey, object: "welcome")
            })
            
        }

        return false
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
        
        SVProgressHUD.dismiss()
    }
    
    func webViewDidStartLoad(webView: UIWebView) {
        
        SVProgressHUD.show()
    }
}


